<template>
  <!-- 跟标签节点 -->
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="query">
        <el-form-item>
          <el-input v-model="query.key" placeholder="部门名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>


    <!--列表-->
    <el-table :data="dataList" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="120" sortable>
      </el-table-column>
      <el-table-column prop="headImage" label="头像" width="220" sortable>
        <template scope="scope">
          <img :src="scope.row.headImage" width="80px">
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="220" sortable>
      </el-table-column>
      <el-table-column prop="age" label="年龄" sortable>
      </el-table-column>
      <el-table-column prop="department.name" label="所属部门" sortable>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
<!--          <el-button type="primary" size="small" @click="handleRole(scope.$index, scope.row)">设置角色</el-button>-->
        </template>
      </el-table-column>
    </el-table>


    <!--分页条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          @size-change="handleSizeChange"
          :total="total" style="float:right;">
      </el-pagination>
    </el-col>

    <!--设置角色界面-->
    <el-dialog title="设置角色" :visible.sync="roleFormVisible" :close-on-click-modal="false">
      <el-form :model="rolesForm" label-width="80px" ref="addForm">
        <el-form-item label="员工名称" prop="name">
          <el-input v-model="rolesForm.username" disabled auto-complete="off"></el-input>
        </el-form-item>
        <!--
         :props="props" 定义前端显示的数据 与 对象 属性是匹配的
         :data="data" 绑定数据源，也就是查出来的权限树
         default-expand-all 默认展开
         ref="tree" 给树形控件取一个名字
       -->
        <el-form-item label="角色" prop="name">
          <el-tree
              :props="props"
              :data="roleData"
              default-expand-all
              node-key="id"
              ref="tree"
              show-checkbox
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="roleFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="employeeRole" >提交</el-button>
      </div>
    </el-dialog>
    <!-- 添加和编辑的弹出框 -->
    <el-dialog :title="title" :visible.sync="formVisible" :close-on-click-modal="false">
      <el-form :model="empForm" label-width="100px" :rules="empFormRules" ref="empForm">
        <el-form-item label="员工用户名" prop="username">
          <el-input v-model="empForm.username" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="empForm.age"></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="empForm.email"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-input v-model="empForm.headImage"></el-input>
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select v-model="empForm.department" value-key="id" clearable filterable placeholder="请选择">
            <el-option
                v-for="dept in depts"
                :key="dept.id"
                :label="dept.name"
                :value="dept">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="formVisible = false">取消</el-button>
        <el-button type="primary" @click.native="formSubmit" :loading="empFormLoading">提交</el-button>
        <el-button type="primary" size="small" @click="handleRole(scope.$index, scope.row)">设置角色</el-button>
      </div>
    </el-dialog>
  </section>

</template>

<script>
import util from "../../common/js/util";
import {addUser, batchRemoveUser} from "../../api/api";

export default {
  name: "Employee",
  data() {
    return {
      query: {
        key: null
      },
      dataList: [],
      listLoading: false,
      sels: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      title: "新增",
      formVisible: false, //默认关闭弹出框
      empForm: {
        id: null,
        username: null,
        password: null,
        headImage: null,
        age: null,
        email: null,
        department_id: null,
        department: null
      },
      empFormRules: {
        username: [
          {required: true, message: '请输入员工名称', trigger: 'blur'}
        ]
      },
      empFormLoading: false,
      depts: [],
      deptTree: [],
      roleData:[],
      props: {
        label: 'name',
        children: 'children'
      },
      roleFormVisible:false, //设置角色弹框默认关闭
      rolesForm:{},
    }
  },
  methods: {
    employeeRole() {
      this.rolesForm.list = this.$refs.tree.getCheckedKeys();
      this.$http.put("/employee/role", this.rolesForm).then(result => {
        if (result.data.success) {
          this.$message.success("绑定成功");
        } else {
          this.$message.error("绑定失败");
        }
      }).catch(result => {
        this.$message.info("网络异常");
      });
      this.roleFormVisible = false;
    },

    //点击设置角色按钮
    handleRole(index, row) {
      this.roleFormVisible = true;
      this.rolesForm.id = row.id;
      this.rolesForm.username = row.username;
      this.getRoleTree();
      this.getRoleIds();
    },
    getRoleIds() {
      this.$http.get("/employee/role/" + this.rolesForm.id).then(res => {
        if (res.data.success) {
          this.$refs.tree.setCheckedKeys(res.data.data);
        } else {
          this.$message.error("回显失败");
        }
      }).catch(res => {
        this.$message.info("网络异常");
      });
    },
    //获取角色树
    getRoleTree() {
      //发送请求
      this.$http.get("/role").then(res => {
        if (res.data.success) {
          this.roleData = res.data.data;
        } else {
          this.$message.error("获取角色列表失败");
        }
      }).catch(res => {
        this.$message.info("网络异常");
      });
    },
    batchRemove() {
      //触发批量删除操作
      var ids = this.sels.map(item => item.id)
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        //let para = { ids: ids };
        this.$http.patch("/employee", ids).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.loadListData();
        });
      }).catch(() => {

      });

    },
    //提交弹出框的效果
    formSubmit() {
      this.$refs.empForm.validate((valid) => {
        if (valid) {//通过表单验证
          this.$confirm('确认提交数据吗？', '提示', {}).then(() => {
            //确认框 用户点击了确认
            this.empFormLoading = true;
            this.$http.put("/employee", this.empForm).then((res) => {

              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
              } else {
                this.$message.error(res.data.message);
              }
              //关闭弹出框
              this.formVisible = false;
              this.loadListData();
              this.empFormLoading = false;

            });
          });
        }
      });


    },
    search() {
      this.loadListData();
    },
    handleAdd() {
      //1.清空表单数据
      this.empForm = {
        id: null,
        username: null,
        password: null,
        headImage: null,
        age: null,
        email: null,
        department_id: null,
        department: null
      }
      //2.打开弹出框
      this.formVisible = true;

    },
    selsChange(sels) {
      console.debug(sels)
      this.sels = sels;
    },
    //性别显示转换
    formatState: function (row, column) {
      //console.debug(row)
      return row.state == 1 ? '启用' : '废弃';
    },
    handleEdit(index, row) {
      //1.做数据的回显
      Object.assign(this.empForm, row);
      //2.打开弹出框
      this.formVisible = true;
    },
    handleDel(index, row) {
      this.$confirm('确认删除数据吗？', '提示', {
        type: 'warning'
      }).then(() => {
        //确认框 用户点击了确认
        this.$http.delete("/employee/" + row.id).then((res) => {
          if (res.data.success) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          } else {
            this.$message.error(res.data.message);
          }
          this.loadListData();
        });
      });
    },
    loadListData() {
      //加载列表数据
      this.listLoading = true
      //封装请求数据
      let query = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        key: this.query.key
      }
      //发送请求获取列表数据
      this.$http.post("/employee", query).then(res => {
        console.log(res)
        this.dataList = res.data.data.data;
        console.log(this.dataList)
        this.total = res.data.data.total;
        //关闭加载效果
        this.listLoading = false;
      }).catch(error => {
      })
    },
    handleCurrentChange(num) {
      this.currentPage = num;
      this.loadListData();
    },
    handleSizeChange(num) {//当用户切换每页展示的条数的时候触发的方法
      this.pageSize = num;
      this.loadListData();
    },
    loadDepts() {
      //发送请求获取所有的部门
      this.$http.get("/dep").then(res => {
        this.depts = res.data.data;
      })
    },
    loadDeptTree() {//加载部门树
      this.$http.get("/dep/tree").then(res => {
        this.deptTree = res.data.data;
      })
    }

  },
  mounted() {
    this.loadListData();
    this.loadDepts();

  }

}

</script>

<style scoped>

</style>
